/**
 *	---------------------------------------------------------------------------
 *	COMP 6231/FALL 2013
 *	Assignment - 02
 *	@author Talha Rahman (1296884)
 *	---------------------------------------------------------------------------
 *	This is a driver class which loads three instances of the RMI server.
 *	@see {@link StationServer}
 *	  
 */

package ca.concordia.comp6231.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import ca.concordia.comp6231.frontend.FrontEnd;

public class UDPService implements Runnable{
	private final int portNo;
	private final FrontEnd frontEnd;
	
	public UDPService(int portNo, FrontEnd frontEnd) {
		this.portNo = portNo;
		this.frontEnd = frontEnd;
	}

	@Override
	public void run() {
		DatagramSocket aSocket = null;
		try {
			aSocket = new DatagramSocket(portNo);
			byte[] buffer = new byte[1000];
			
			while (true) {
				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(request);
				processRequest(aSocket, request, frontEnd);
			}
		} catch (SocketException e) {
			System.out.println("Socket error: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO error: " + e.getMessage());
		} finally {
			if (aSocket != null)
				aSocket.close();
		}		
	}
	
	private void processRequest(DatagramSocket socket, DatagramPacket request, FrontEnd frontEnd){
			
			UDPServiceRequestProcessor requestProcessorThread 
						= new UDPServiceRequestProcessor(frontEnd, socket, request);
			requestProcessorThread.start();
		}
}
